import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
  // console.log(to)
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.state.user.userInfo.id) {
        // 获取登录信息
        await store.dispatch('user/getUserInfo')
        // 获取动态路由
        await store.dispatch('permission/getUserPermissions')
        const menus = store.state.permission.userPerm.menus
        const routes = await store.dispatch('permission/filterRoutes', menus)
        console.log('允许访问的页面', routes)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      }
      next()
    }
  } else {
    if (to.path === '/login' || to.path === '/404' || to.path === '/register') {
      next()
    } else {
      next('/login')
    }
  }
})
